package com.sunny.ynhz.ui.patrol.problems.draft;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.MoreStyleAdapter;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.api.okhttp.OkHttpHelper;
import com.sunny.ynhz.bean.FileBean;
import com.sunny.ynhz.bean.ImageBean;
import com.sunny.ynhz.bean.PatrolMoreStyleBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.ui.base.BaseFragment;
import com.sunny.ynhz.ui.patrol.PatrolRiverMoreStyleActivity;
import com.sunny.ynhz.utils.BeanUtils;
import com.sunny.ynhz.utils.PictureUtil;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 巡河多样化fragment
 * Created by luao on 2017/7/24.
 */

public class MoreStyleDraftFragment extends BaseFragment {

    @BindView(R.id.problem_draft_recycle)
    RecyclerView problemDraftRecycle;
    private RealmResults<PatrolMoreStyleBean> moreStyleList;
    private MoreStyleAdapter mMoreStyleAdapter;
    private Realm mRealm;

    String imgs = "";
    String files = "";

    String filenames = "";

    public static MoreStyleDraftFragment getInstance() {
        return new MoreStyleDraftFragment();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_problem_draft;
    }

    @Override
    protected void init() {
        super.init();
        String userId = SPUtil.get("userId","null").toString();
        mRealm = RealmUtils.getDeleteRealm();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity);
        problemDraftRecycle.setLayoutManager(linearLayoutManager);
        moreStyleList = mRealm.where(PatrolMoreStyleBean.class).equalTo("userId",userId).findAllAsync();
        mMoreStyleAdapter = new MoreStyleAdapter(moreStyleList);
        problemDraftRecycle.setAdapter(mMoreStyleAdapter);
        moreStyleList.addChangeListener(new RealmChangeListener<RealmResults<PatrolMoreStyleBean>>() {
            @Override
            public void onChange(RealmResults<PatrolMoreStyleBean> patrolBeen) {
                mMoreStyleAdapter.notifyDataSetChanged();
            }
        });

        mMoreStyleAdapter.setOnItemClick(new MoreStyleAdapter.OnItemClick() {
            @Override
            public void onUpLoadClicked(final PatrolMoreStyleBean data) {
                // TODO: 2017/11/16  上传逻辑写在这里
                filenames="";
                if (TextUtils.isEmpty(data.getDescribe())) {
                    ToastUtils.SingleToastUtil(MoreStyleDraftFragment.this.getContext(), "描述不能为空");
                    return;
                }
                if (TextUtils.isEmpty(data.getTm())) {
                    ToastUtils.SingleToastUtil(MoreStyleDraftFragment.this.getContext(), "时间不能为空");
                    return;
                }
                if (data.getFileUrl().isEmpty() && data.getPicUrl().isEmpty()) {
                    ToastUtils.SingleToastUtil(MoreStyleDraftFragment.this.getContext(), "文件类或图片类必须要提交一个");
                    return;
                }

                ArrayList<String> imagesPath = new ArrayList<>();
                ArrayList<String> filePath = new ArrayList<>();

                String[] images=data.getPicUrl().split(",");
                if (!data.getPicUrl().isEmpty()) {
                    imagesPath.clear();
                    imagesPath.addAll(new ArrayList<String>(java.util.Arrays.asList(images)));
                }
                String[] filepaths=data.getFileUrl().split(",");
                if (!data.getFileUrl().isEmpty()) {
                    filePath.clear();
                    filePath.addAll(new ArrayList<String>(java.util.Arrays.asList(filepaths)));
                }

                Observable<FileBean> fileBeanObservable = uploadFile(pathToFile(filePath));
                Observable<ImageBean> imageBeanObservable = uploadImgs(pathToFile(imagesPath));
                Observable.merge(fileBeanObservable, imageBeanObservable).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Object>() {
                    @Override
                    public void onCompleted() {
                        upLoadMsg(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        ShowUtils.closePopwindow();

                    }

                    @Override
                    public void onNext(Object o) {
                        if (o instanceof ImageBean) {
                            ImageBean image = (ImageBean) o;

                            if (TextUtils.isEmpty(imgs)) {
                                imgs = NetUrl.imageBaseUrl + image.getNewPath();
                            } else {
                                imgs = NetUrl.imageBaseUrl + image.getNewPath() + "," + imgs;
                            }

                        } else if (o instanceof FileBean) {
                            FileBean image = (FileBean) o;
                            if (TextUtils.isEmpty(files)) {
                                files = NetUrl.imageBaseUrl + image.getNewPath();
                            } else {
                                files = NetUrl.imageBaseUrl + image.getNewPath() + "," + files;
                            }
                        }
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        ShowUtils.inItPopwin(MoreStyleDraftFragment.this.getContext(), "请等待");
                    }
                });
            }

            @Override
            public void onDeleteClicked(PatrolMoreStyleBean data) {
                mRealm.beginTransaction();
                data.deleteFromRealm();
                mRealm.commitTransaction();
            }

            @Override
            public void onItemClick(PatrolMoreStyleBean data) {
                Intent intent = new Intent(activity, PatrolRiverMoreStyleActivity.class);
                intent.putExtra("moreStyleId", data.getId());
                startActivity(intent);
            }
        });

    }

    private Observable<FileBean> uploadFile(List<File> mlist) {
        return Observable.from(mlist).flatMap(new Func1<File, Observable<FileBean>>() {
            @Override
            public Observable<FileBean> call(File file) {
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

                if (TextUtils.isEmpty(filenames)) {
                    filenames = file.getName();
                } else {
                    filenames = file.getName() + "," + filenames;
                }

                return HttpManager.getInstance().uploadFiles(System.currentTimeMillis() + "", body);
            }
        });
    }

    public List<File> pathToFile(ArrayList<String> filePath) {
        List<File> files = new ArrayList<>();
        for (int i = 0; i < filePath.size(); i++) {
            files.add(new File(filePath.get(i)));
        }
        return files;
    }

    private Observable<ImageBean> uploadImgs(final List<File> mlist) {
        return Observable.from(mlist).flatMap(new Func1<File, Observable<ImageBean>>() {
            @Override
            public Observable<ImageBean> call(File file) {
                //压缩图片
                Bitmap bitmap = PictureUtil.getSmallBitmap(file.getPath());
                File fileCompressed = PictureUtil.compressImage(bitmap, file.getName());

                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), fileCompressed);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                return HttpManager.getInstance().uploadImgs("www", body);
            }
        });
    }

    @TargetApi(24)
    public void upLoadMsg(final PatrolMoreStyleBean data) {
        PatrolMoreStyleBean patrolMoreStyleBean = new PatrolMoreStyleBean();
        patrolMoreStyleBean.setUserId(data.getUserId());
        patrolMoreStyleBean.setPicUrl(imgs);
        patrolMoreStyleBean.setPicNums(data.getPicNums());
        patrolMoreStyleBean.setFileUrl(files);
        patrolMoreStyleBean.setFileNums(data.getFileNums());
        patrolMoreStyleBean.setFileName(filenames);
        patrolMoreStyleBean.setDescribe(data.getDescribe());
        patrolMoreStyleBean.setTm(data.getTm()+":00");
        OkHttpHelper.postAsyn(NetUrl.baseUrl + "patrolOther/insertPatrolOther", BeanUtils.objectToMap(patrolMoreStyleBean), new OkHttpHelper.ResultCallback<String>() {
            @Override
            public void onResponse(String response) {
                ShowUtils.closePopwindow();

                mRealm.beginTransaction();
                PatrolMoreStyleBean patrolMoreStyleBeanWithDel= mRealm.where(PatrolMoreStyleBean.class).equalTo("id",data.getId()).findFirst();
                if(patrolMoreStyleBeanWithDel != null)
                    patrolMoreStyleBeanWithDel.deleteFromRealm();
                mRealm.commitTransaction();

                ToastUtils.SingleToastUtil(MoreStyleDraftFragment.this.getContext(), "提交成功");
            }

            @Override
            public void onError(Request request, Exception e) {
                super.onError(request, e);
                ShowUtils.closePopwindow();
                ToastUtils.SingleToastUtil(MoreStyleDraftFragment.this.getContext(), "提交失败");
            }

            @Override
            public void onAfter() {
                super.onAfter();
            }

            @Override
            public void onBefore(Request request) {
                super.onBefore(request);
            }
        }, this);
    }
}
